package bearworker.zxl.utils;

import com.google.gson.Gson;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by 逍遥的熊 on 2017/11/26.
 */
public class HttpUtil {

    private Logger logger = Logger.getLogger(HttpUtil.class);

    private static Gson gson = new Gson();

    private ChannelHandlerContext ctx;

    public HttpUtil(ChannelHandlerContext ctx){
        this.ctx = ctx;
    }

    public void httpRes(int resCode,Object resData){
        String resStr = "";
        if(resData instanceof String){
            resStr = (String) resData;
        }else {
            resStr = gson.toJson(resData);
        }

        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(resCode));

        ByteBuf buf = Unpooled.copiedBuffer(resStr,
                CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        io.netty.handler.codec.http.HttpUtil.setContentLength(res, res.content().readableBytes());

        ChannelFuture f = ctx.channel().writeAndFlush(res);

        f.addListener(ChannelFutureListener.CLOSE);
    }
}
